package com.dns.customers.service.impl;

import com.customer.dns.client.CuCustomerService;
import com.customer.dns.client.CuCustomerServicePortType;
import com.dns.customers.AppPage;
import com.dns.customers.DnsTask;
import com.dns.customers.dao.CustomerDao;
import com.dns.customers.dao.DomainDao;
import com.dns.customers.model.CustomerDomain;
import com.dns.customers.model.Customers;
import com.dns.customers.model.User;
import com.dns.customers.service.CustomerDnsService;
import com.dns.framework.data.DataMap;
import com.dns.framework.data.IData;
import com.dns.framework.data.IDataset;
import com.dns.framework.page.Pagination;
import com.google.gson.JsonObject;
import com.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author :  yulei
 * @data :  2018/5/19 10:26
 * @Version :  1.0
 **/


@Service
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
public class CustomerDnsServiceImpl extends AppPage implements CustomerDnsService  {

    @Autowired
    CustomerDao customerDao;
    @Autowired
    DomainDao domainDao;
    @Autowired
    CuCustomerService cuCustomerService;

    @Autowired
    DomainServiceImpl domainService;
    @Autowired
    private DataSourceTransactionManager transactionManager;


    static {
        //忽略SSL认证
        try {
            SSLUtils.ignoreSsl();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建客户
     * @param request
     * @return
     */
    @Override
    public String createCustAccount(HttpServletRequest request) {

        //自定义事务，手动提交事务
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);// 事物隔离级别，开启新事务
        TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态
        TransactionStatus domainRecordStatus = null;

        JSONObject resultJSON = new JSONObject();
        JSONObject message = new JSONObject();

        InputStream is = null;
        try {
            is = request.getInputStream();
            //前台传递的流数据
            String requestStr = IOUtils.toString(is, "utf-8");
            log.debug("contentStr: " + requestStr);
            JSONObject requestJson = JSONObject.fromObject(requestStr);
            //管理客户ID
            String custManagerId = requestJson.getString("cust_manager_id");
            //构建管理客户对象
            User managerUser = domainService.buildUserObject(custManagerId);
            //待创建的客户信息
            JSONArray accountJsons = requestJson.getJSONArray("account");
            //取出数组中的一个，因为只有一个客户
            JSONObject accountJson = accountJsons.getJSONObject(0);
            //要创建的客户ID信息
            String custId = accountJson.getString("loginName");
            String ip=accountJson.getString("ip");
            accountJson.put("loginPwd",DesUtil.base64Decode(accountJson.getString("loginPwd")));
            // 判断客户是否存在
            boolean isExists=  customerDao.checkIsExistsByCustId(custId);
            if(isExists){
                message.put("errorCode", "8888");
                message.put("errorMsg",  "大客户已存在");
                resultJSON.put("result", message);
                return resultJSON.toString();
            }

            //域名信息
            JSONObject custDomainJson = accountJson.getJSONObject("customerDomain");
            log.debug("custDomainJson: " + custDomainJson);
            /*********************************************************************/
            /*                         第一步： 大客户创建 START                   */
            /*********************************************************************/
            //customers节点，为转换xml字符串，调润通接口使用.
            JSONObject custJson = new JSONObject();
            custJson.put("account", accountJsons);
            custJson.put("user", managerUser);
            //过滤空节点
            custJson = JsonUtils.jsonFilterNull(custJson);

            //1、操作本地数据库
            String dbResult = customerDao.addCustomerAccount(custJson.toString());
            if (!dbResult.contains("成功")){
                message.put("errorCode", "保存异常");
                message.put("errorMsg", dbResult);
                resultJSON.put("result", message);
                return resultJSON.toString();
            }

            //为添加根域名记录信息时使用.
            JSONObject recordCustDomain =new JSONObject();
            JSONArray  recordRootDomain =new JSONArray();
            recordCustDomain.put("rootDomain",recordRootDomain);

            JSONObject customerJson = new JSONObject();
            custJson.remove("account");
            //重新添加过滤后的accountJsons
            custJson.put("account", accountJsons);
            customerJson.put("customers", custJson);
            log.debug("customerJson: " + customerJson);

            //2、调用润通接口
            JSONObject custResponseJson = invokeRTWebService(customerJson, ADD_CUSTOMER_ACCOUNT);
            JSONObject results = (JSONObject) custResponseJson.get("results");
            JSONArray result = (JSONArray) results.get("result");
            //只返回一个ressult节点，只取第一个节点即可
            JSONObject resultJson = result.getJSONObject(0);
            //有returncode表示业务办理失败
            if (resultJson.containsKey("returncode")) {
                String resultcode = resultJson.getString("returncode");
                message.put("errorCode", resultcode);
                message.put("errorMsg", resultJson.getString("errorMsg"));
                resultJSON.put("result", message);
                //业务办理失败，回滚事务
                transactionManager.rollback(status);
                return resultJSON.toString();
            }else{
                transactionManager.commit(status);
            }

            /*********************************************************************/
            /*                       第一步： 大客户创建 END                       */
            /*********************************************************************/

            message.put("errorCode", "0000");
            message.put("errorMsg",  "创建大客户操作成功!");
            resultJSON.put("result", message);
        } catch (Exception e) {
            log.error("创建大客户操作异常：", e);
            message.put("errorCode", "8888");
            message.put("errorMsg", e.getMessage());
            resultJSON.put("result",message);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {

            return resultJSON.toString();
        }

    }
    /**
     * 修改大客户账户信息
     * @param customers
     * @return
     */
    @Override
    public String modifyCustomerAccount(HttpServletRequest request,String customers) {
        //返回前台的JSON串
        JSONObject resultJSON = new JSONObject();
        JSONObject message = new JSONObject();
        try {
            log.debug("customers:"+customers);
            JSONObject customersJson = JSONObject.fromObject(customers);
            JSONObject customersJSON = customersJson.getJSONObject("customers");
            //***过滤JSON中的空值***
            JSONObject custJson = JsonUtils.jsonFilterNull(customersJSON);

            //************** 客户信息校验START*************
            JSONArray accounts = custJson.getJSONArray("account");
            if (accounts == null || accounts.size() <= 0){
                message.put("errorMsg","参数异常");
                message.put("errorCode","参数异常");
                resultJSON.put("result",message);
                return resultJSON.toString();
            }
            for (int i=0;i<accounts.size();i++){
                JSONObject account = accounts.getJSONObject(i);
                String custId = account.getString("loginName");
                //如果id存在就修改，不在就不允许修改
                if (customerDao.queryUserById(custId)==null){
                    log.debug(custId+"客户不存在");
                    message.put("errorMsg", custId+"客户不存在");
                    message.put("errorCode", custId+"客户不存在");
                    resultJSON.put("result", message);
                    return resultJSON.toString();
                }
            }
            //查询管理员
            Map<String,Object> userMap = customerDao.queryUserById(custJson.getString("cust_manager_id"));
            if (userMap == null){
                message.put("errorMsg", "管理客户不存在");
                message.put("errorCode", "管理客户不存在");
                resultJSON.put("result", message);
                return resultJSON.toString();
            }
            //************** 客户信息校验END****************

            //**************调用润通接口START**************************
            //拼接成润通接口需要的参数格式
            StringBuffer runTongJson = new StringBuffer();
            runTongJson.append("{\"customers\":" +
                    "{\"user\":{" +
                    "\"name\":\""+userMap.get("CUST_ID")+"\"," +
                    "\"password\":\""+userMap.get("CUST_PASSWORD")+"\"," +
                    "\"accessIp\":\""+getAccess_ip()+"\"}," +
                    "\"account\":[");
            int a=0,b=0,c=0;
            for (int i = 0;i<accounts.size();i++){
                JSONObject account = accounts.getJSONObject(i);
                if (a>0){
                    runTongJson.append(",");
                }
                runTongJson.append("{");
                runTongJson.append("\"loginName\":\""+account.getString("loginName")+"\",");
                runTongJson.append("\"company\":\""+account.getString("company")+"\",");
                runTongJson.append("\"tel\":\""+account.getString("tel")+"\",");
                runTongJson.append("\"phone\":\""+account.getString("phone")+"\",");
                runTongJson.append("\"email\":\""+account.getString("email")+"\",");
                runTongJson.append("\"configCount\":\""+account.getString("configCount")+"\",");
                runTongJson.append("\"flushCount\":\""+account.getString("flushCount")+"\",");
                runTongJson.append("\"resolvCount\":\""+account.getString("resolvCount")+"\",");
                String pwd = DesUtil.base64Decode(account.getString("loginPwd"));
                runTongJson.append("\"loginPwd\":\""+pwd+"\",");
                runTongJson.append("\"ip\":\""+account.getString("ip")+"\",");
                runTongJson.append("\"emerencyConTract\":\""+account.getString("emerencyConTract")+"\",");
                runTongJson.append("\"emerencyContractTel\":\""+account.getString("emerencyContractTel")+"\",");
                runTongJson.append("\"custManager\":\""+account.getString("custManager")+"\",");
                runTongJson.append("\"custManagerTel\":\""+account.getString("custManagerTel")+"\",");
                runTongJson.append("\"companyAddress\":\""+account.getString("companyAddress")+"\",");
                runTongJson.append("\"customerDomain\":{\"rootDomain\":[");
                if (account.has("rootDomains")){
                    JSONArray rootDomains = account.getJSONArray("rootDomains");
                    b=0;
                    for (int j=0;j<rootDomains.size();j++){
                        JSONObject rootDomain = rootDomains.getJSONObject(j);

                        if (b>0){
                            runTongJson.append(",");
                        }
                        runTongJson.append("{");
                        runTongJson.append("\"domainName\":\""+rootDomain.getString("domainName")+"\",");
                        if (rootDomain.has("remark")){
                            runTongJson.append("\"remark\":\""+rootDomain.getString("remark")+"\",");
                        }
                        runTongJson.append("\"record\":[");
//                        if (rootDomain.get("records")!=null){
//                            JSONArray records = rootDomain.getJSONArray("records");
//                            c=0;
//                            for (int k=0;k<records.size();k++){
//                                JSONObject record = records.getJSONObject(k);
//                                if (c>0){
//                                    runTongJson.append(",");
//                                }
//                                runTongJson.append("{\"res\":\""+record.getString("res")+"\",");
//                                runTongJson.append("\"type\":\""+record.getString("type")+"\"}");
//                                c++;
//                            }
//                        }
                        runTongJson.append("]");
                        runTongJson.append("}");
                        b++;
                    }
                }
                runTongJson.append("]}}");
                a++;
            }
            runTongJson.append("]}}");
            log.debug("runTongJson:"+runTongJson);
            JSONObject runTongJsonXML = JSONObject.fromObject(runTongJson.toString());
            //取出JSON对象的cusomers对象
            JSONObject customerJson = (JSONObject) runTongJsonXML.get("customers");
            String res = customerDao.modifyCustomerAccount(request,customerJson.toString());
            if(res.contains("成功")){
                //***将前台传递的JSON字符串转换为XML字符串***
                JSONObject queryDnsResultJson = JsonUtils.jsonFilterNull(runTongJsonXML);
                //**************调用润通接口START**************************
                resultJSON=invokeRTWebService(queryDnsResultJson,ADD_CUSTOMER_ACCOUNT);

                //获取客户域名信息
                JSONObject results= (JSONObject) resultJSON.get("results");
                //result节点信息处理
                JSONArray result = results.getJSONArray("result");
                JSONObject messageInfo=result.getJSONObject(0);
                //没有returncode表示业务办理成功
                if (messageInfo.containsKey("returncode")){
                    String resultcode = messageInfo.getString("returncode");
                    message.put("errorCode", resultcode);
                    message.put("errorMsg", messageInfo.getString("errorMsg"));
                    resultJSON.put("result", message);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return resultJSON.toString();
                }
                //*********** 润通创建客户成功,联通DNS本地数据库保存一份 START************

                //业务办理成功
                message.put("errorMsg",res);
                resultJSON.put("result",message);
            }else{
                message.put("errorMsg","修改客户信息失败");
                message.put("errorCode","修改客户信息异常");
                resultJSON.put("result",message);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        catch (Exception e){
            log.error("修改客户信息异常:\n",e);
            message.put("errorMsg","修改客户信息异常:"+e);
            message.put("errorCode","修改客户信息异常:"+e);
            resultJSON.put("result",message);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

        }
        finally {
            return  resultJSON.toString();
        }
    }
    /**
     * 删除大客户信息，包含两个操作.
     * 1、删除已添加的大客户账户
     * 2、删除已添加的大客户账户中已配置的根域名
     * @param customers
     * @return
     * @throws Exception
     */
    @Override
    public String delCustomerAccount(HttpServletRequest request,String customers) {
        //返回前台的JSON串
        JSONObject resultJSON = new JSONObject();
        JSONObject message = new JSONObject();
        try {
            JSONObject customersJson = JSONObject.fromObject(customers);

            //***将前台传递的JSON字符串转换为XML字符串***
            JSONObject custJson = JsonUtils.jsonFilterNull(customersJson);
            //将JSON 数据 转换为JavaBean

            //取出JSON对象的cusomers对象
            JSONObject customerJson = (JSONObject) custJson.get("customers");
            log.debug("customerJson = " + customerJson);
            Map<String,Object> userMap = customerDao.queryUserById(customerJson.getString("cust_manager_id"));
            JSONObject userJSON = new JSONObject();
            if (userMap == null){
                message.put("errorMsg", "没有查询到客户信息");
                message.put("errorCode", "没有查询到客户信息");
                resultJSON.put("result", message);
                return resultJSON.toString();
            }else{
                userJSON.put("name",userMap.get("CUST_ID"));
                userJSON.put("password",userMap.get("CUST_PASSWORD"));
                userJSON.put("accessIp",getAccess_ip());
            }
            customerJson.put("user",userJSON);
            customerJson.remove("custId");



            //1、删除本地数据库存储的数据
            String daoMsg = customerDao.deleteCustomerAccount(request,customerJson.toString());
            //2、调用润通接口删除大客户信息

            //**************调用润通接口START**************************
            JSONObject custResponseJson = invokeRTWebService(custJson, DEL_CUSTOMER_ACCOUNT);
            JSONObject results = (JSONObject) custResponseJson.get("results");
            JSONArray result = (JSONArray) results.get("result");
            //只返回一个ressult节点，只取第一个节点即可
            JSONObject resultJson = result.getJSONObject(0);
            //有returncode表示业务办理失败
            if (resultJson.containsKey("returncode")){
                if (resultJson.getString("errorMsg").contains("不存在")){
                    message.put("errorMsg",daoMsg);
                    resultJSON.put("result", message);
                }else{
                    //事物回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //第二种
                    message.put("errorCode", resultJson.getString("returncode"));
                    message.put("errorMsg", resultJson.getString("errorMsg"));
                    resultJSON.put("result", message);
                }
            }
            else{
                message.put("errorMsg",daoMsg);
                resultJSON.put("result", message);
            }
        } catch (Exception e) {
            message.put("errorMsg","删除客户信息异常:"+e);
            message.put("errorCode","删除客户信息异常:"+e);
            resultJSON.put("result",message);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //第二种
            e.printStackTrace();
        } finally {
            return resultJSON.toString();
        }
    }

    /**
     * 分页查询大客户列表
     * @param request
     * @return
     */
    @Override
    public String queryCustListByName(HttpServletRequest request) {
        JSONObject resultJson = new JSONObject();
        JSONObject message = new JSONObject();
        try {
            //客户名称
            String custName = request.getParameter("CUST_NAME");
            //当前页
            int currPage = Integer.parseInt(request.getParameter("CURRENT_PAGE_NUMBER"));
            //每页显示的记录数
            int pageSize = Integer.parseInt(request.getParameter("PAGE_SIZE"));
            //记录总数
            int rowCount = Integer.parseInt(request.getParameter("ROW_COUNT"));
            Pagination pagination = new Pagination();
            pagination.setCurrPage(currPage);
            pagination.setPageSize(pageSize);
            pagination.setRowCount(rowCount);

            IDataset result = customerDao.queryCustListByName(custName, pagination);

            int rowCounts = result.getCount();
            pagination.setRowCount(rowCounts);
            message.put("reusultcode", "0000");
            message.put("message", "查询客户信息成功");
            //将结果信息存放起来
            message.put("CUST_INFO", result.getResultList());
            resultJson.put("result", message);
            resultJson.put("ROW_COUNT", rowCounts);//记录总数
            resultJson.put("PAGE_COUNT", pagination.getPageCount());//总页数

        } catch (Exception e) {
            log.error("查询客户信息异常:", e);
            message.put("reusultcode", "8888");
            message.put("message", e.getMessage());
            resultJson.put("result", message);
        } finally {
            return resultJson.toString();
        }
    }
    /**
     * 查询大客户信息（包含域名信息）
     * @param custId
     * @return
     */
    @Override
    public String queryAccoundDomain(String custId){
        JSONObject result = null;
        try{
            Map<String,Object> map = customerDao.queryAccoundDomain(custId);
            result = JSONObject.fromObject(map);
        }catch (Exception e){
            result = new JSONObject();
            result.put("errorMsg","查询异常");
            result.put("errorCode","查询异常");
            e.printStackTrace();
        }finally {
            return result.toString();
        }
    }
    /**
     * 分页查询根域名详情
     * @param custId 客户id
     * @return
     */
    @Override
    public String queryRootDomainPage(String  custId,int currPage,int pageSize){
        JSONObject resultJSON = new JSONObject();
        JSONObject errorMsg = new JSONObject();
        try{
            if (custId == null || "".equals(custId)){
                resultJSON.put("errorMsg","参数异常");
                resultJSON.put("errorCode","参数异常");
                return resultJSON.toString();
            }
            Pagination pagination = new Pagination();
            pagination.setCurrPage(currPage);
            pagination.setPageSize(pageSize);
            IDataset result = customerDao.queryRootDomainPage(custId,pagination);
            int rowCounts = result.getCount();
            pagination.setRowCount(rowCounts);
            //将结果信息存放起来
            resultJSON.put("errorMsg","查询成功");
            resultJSON.put("data", result.getResultList());
            resultJSON.put("ROW_COUNT", rowCounts);//记录总数
            resultJSON.put("PAGE_COUNT", pagination.getPageCount());//总页数

        }catch(Exception e){
            resultJSON.put("errorMsg","查询异常");
            resultJSON.put("errorCode","查询异常");
        }
        return resultJSON.toString();
    }

    /**
     * 查询所有域名类型
     * @return
     */
    @Override
    public String getDnsResTypes() {
        JSONArray result = new JSONArray();
        try {
            Map param = new HashMap();
            param.put("VALIDFLAG","0"); //0 表示有效
            List<Map<String,Object>> areaList = customerDao.getDnsResTypes(param);
            for( Map<String,Object> areaResult:areaList){
                JSONObject areaJson= JSONObject.fromObject(areaResult);
                result.add(areaJson);
            }
        }catch (Exception e){
            log.error("查询域名类型信息异常: ",e);
            result.add("8888");
        }finally {
            return result.toString();
        }
    }
    /**
     * 查询大客户账户信息
     * @param custId
     * @return
     */
    @Override
    public String queryCustomerAccount(String custId) {
        String result=null;
        try {
            List<Map<String ,Object>> custResultList=  customerDao.queryCustomerAccount(custId);
            if(null!=custResultList){
                //因客户只有一个，所有取第一个元素即可
                Map<String,Object> custResult=custResultList.get(0);
                JSONObject custResultJson= JSONObject.fromObject(custResult);
                result=custResultJson.toString();
            }else{
                result="无此客户信息: "+custId;
            }
        }
        catch (Exception e){
            log.error("查询客户信息异常：",e);
        }finally {
            return result;
        }
    }
    /**
     * 根据客户ID查询根域名和子域名及其解析类型
     * @param custId
     * @return
     */
    @Override
    public String queryDomainnameAndType(String custId) {
        String result = null;
        JSONArray resultJSONArray = new JSONArray();       //user的value值，即根域名列表
        try {
            List<Map<String, Object>> parentnameResultList = customerDao.queryParentname(custId);  //先查根域名，返回根域名的列表
            if (parentnameResultList == null) {
                return "[]";
            }
            //将子域名放到对应的根域名下
            for (Map<String, Object> domain : parentnameResultList) {
                if ("0".equals(domain.get("domain_type"))) {
                    String domainName = (String) domain.get("domain_name");
                    if (domainName == null || "".equals(domainName))
                        continue;
                    JSONArray childList = domainDiGui(parentnameResultList,domainName);
                    domain.put("children", childList);
                    resultJSONArray.add(domain);
                }
            }
            System.out.println(resultJSONArray.toString());
            return resultJSONArray.toString();
        } catch (Exception e) {
            log.error("查询域名及类型信息异常：", e);
            return "[]";
        }
    }
    /**
     * 递归将子域名放入父域名中
     * @param parentnameResultList
     * @param domainName
     * @return
     */
    public JSONArray domainDiGui(List<Map<String, Object>> parentnameResultList,String domainName){
        JSONArray jsonList = new JSONArray();
        if(parentnameResultList == null){
            return null;
        }
        for (Map<String, Object> domain : parentnameResultList) {
            String name = (String)domain.get("parent_domain_name");
            String childName = (String)domain.get("domain_name");
            if(name != null && name.equals(domainName)){
                JSONArray childList =  domainDiGui(parentnameResultList,childName);
                if(childList != null && childList.size()>0){
                    domain.put("children", childList);
                }
                jsonList.add(domain);
            }
        }
        return jsonList;
    }

    /**
     * 根据客户id查询未完成的订单信息
     * @param custId 客户
     * @return
     */
    @Override
    public String getOrderInfoByCustId(String custId) {
        JSONArray result = new JSONArray();
        try {
            //查询处于在途中的解析类订单任务
            Map param = new HashMap();
            param.put("CUST_ID",custId);
            param.put("TASK_TYPE",DnsTask.TASK_TYPE_RES); //订单类型,解析类型
            //查询处于订单状态中的任务
            List statusList= Arrays.asList
                    (DnsTask.TASK_ISSUEING,DnsTask.TASK_NOT_EXECUTE,DnsTask.TASK_EXECUTING);
            param.put("TASK_STATUS",statusList);
            List<Map<String,Object>> orderResList = customerDao.getOrderInfoByCustId(param);
            if (orderResList != null){
                for (Map<String,Object> order : orderResList){
                    String valitime = order.get("validTime")+"";
                    int tt = 0;
                    try{
                        tt = Integer.parseInt(valitime.trim());
                    }catch (Exception e){
                        tt = 66;
                    }
                    if (tt < 60){
                        result.add(order);
                    }
                }
            }
        }catch (Exception e){
            log.error("查询客户订单信息异常: ",e);
            result.add("8888");
        }finally {
            return result.toString();
        }
    }
    /**
     * 根据客户ID和域名类型查询客户归属的域名信息
     * @param custId, domain_type
     * @return
     */
    @Override
    public String queryDomainnameByIDAndType(String custId, String domain_type) {
        String result=null;
        JSONArray resultJSON = new JSONArray();
        try {
            List<Map<String ,Object>> domainnameResultList=  customerDao.queryDomainnameByIDAndType(custId, domain_type);
            if(null!=domainnameResultList&&domainnameResultList.size()!=0){
                for( Map<String,Object> nameResult:domainnameResultList){
                    JSONObject nameResultJson= JSONObject.fromObject(nameResult);
                    resultJSON.add(nameResultJson);
                }
                result = resultJSON.toString();
            }else{
                result="无域名信息: "+custId;
            }
        }
        catch (Exception e){
            log.error("查询域名信息异常：",e);
        }finally {
            return result;
        }
    }
    /**
     * 根据客户ID分页查询域名列表
     * @param request,
     * @return
     */
    @Override
    public String queryRecordInfo(HttpServletRequest request) {
        JSONObject resultJson = new JSONObject();
        JSONObject message = new JSONObject();
        try {
            //客户ID
            String custId= request.getParameter("custId");
            String cpageStr = request.getParameter("CURRENT_PAGE_NUMBER");
            //当前页
            int currPage = Integer.parseInt(cpageStr);
            //每页显示的记录数
            int pageSize = Integer.parseInt(request.getParameter("PAGE_SIZE"));
            Pagination pagination = new Pagination();
            pagination.setCurrPage(currPage);
            pagination.setPageSize(pageSize);
            //分页结果集
            IDataset result=  customerDao.queryRecordInfo(custId,pagination);

            int rowCounts = result.getCount();
            pagination.setRowCount(rowCounts);
            message.put("reusultcode", "0000");
            message.put("message", "查询域名记录成功");
            //将结果信息存放起来
            message.put("DOMAIN_RECORDS", result.getResultList());
            resultJson.put("result", message);
            resultJson.put("ROW_COUNT", rowCounts);//记录总数
            resultJson.put("PAGE_COUNT", pagination.getPageCount());//总页数

        }
        catch (Exception e){
            log.error("查询域名记录异常：",e);
            message.put("reusultcode", "8888");
            message.put("message", "查询域名记录异常:"+e.getMessage());
            resultJson.put("result", message);
        }
        finally {
            return resultJson.toString();
        }
    }
    /**
     * 根据多个条件查询订单及其详细信息
     * @param request
     * @return
     */
    @Override
    public String queryOrder(HttpServletRequest request)  {
        JSONObject resultJson = new JSONObject();
        JSONObject message = new JSONObject();
        try {
            String orderId =request.getParameter("orderId");
            String custId =request.getParameter("custId");
            String domainname =request.getParameter("domainname");
            String createTime1 =request.getParameter("createTime1");
            String createTime2 =request.getParameter("createTime2");
            String taskStatus =request.getParameter("taskStatus");
            IData param =new DataMap();
            param.put("orderId",orderId);
            param.put("custId",custId);
            param.put("domainname",domainname);
            param.put("createTime1","undefined".equals(createTime1)?"":createTime1);
            param.put("createTime2","undefined".equals(createTime2)?"":createTime2);
            param.put("taskStatus",taskStatus);
            int currPage = Integer.parseInt(request.getParameter("CURRENT_PAGE_NUMBER"));
            //每页显示的记录数
            int pageSize = Integer.parseInt(request.getParameter("PAGE_SIZE"));
            //记录总数
            int rowCount = Integer.parseInt(request.getParameter("ROW_COUNT"));
            Pagination pagination = new Pagination();
            pagination.setCurrPage(currPage);
            pagination.setPageSize(pageSize);
            IDataset result=  customerDao.queryOrder(param,pagination);
            JSONArray orderJSONArray =new JSONArray();
            List<Map<String,Object>> orderResultList =result.getResultList();
            for(Map<String, Object> orderResult : orderResultList){
                JSONObject orderJSON = JSONObject.fromObject(orderResult);
                String taskType = (String) orderJSON.get("task_type");
                switch(taskType){
                    case "0":
                        orderJSON.put("task_type", "域名解析");
                        break;
                    case "1":
                        orderJSON.put("task_type", "缓存刷新");
                        break;
                    default: break;
                }
                String taskStauts = (String) orderJSON.get("task_status");
                switch(taskStauts){
                    case "1":
                        orderJSON.put("task_status", "下发中");
                        break;
                    case "2":
                        orderJSON.put("task_status", "未执行");
                        break;
                    case "3":
                        orderJSON.put("task_status", "执行中");
                        break;
                    case "4":
                        orderJSON.put("task_status", "任务完成");
                        break;
                    case "5":
                        orderJSON.put("task_status", "任务失败");
                        break;
                    default: break;
                }
                orderJSONArray.add(orderJSON);
            }
            int rowCounts = result.getCount();
            pagination.setRowCount(rowCounts);
            //将结果信息存放起来
            resultJson.put("ROW_COUNT", rowCounts);//记录总数
            resultJson.put("PAGE_COUNT", pagination.getPageCount());//总页数
            message.put("reusultcode","0000");
            message.put("message","查询域名记录成功");
            message.put("ORDER_INFOS",orderJSONArray);
            resultJson.put("result",message);
        }
        catch (Exception e){
            log.error("查询订单信息异常：",e);
            message.put("reusultcode","0000");
            message.put("message","查询订单信息异常:"+e.getMessage());
            resultJson.put("result",message);
        }finally {
            return resultJson.toString();
        }
    }
    /**
     * 查看订单详情
     * @param orderId
     * @return
     */
    @Override
    public String  queryOrderMore(String orderId) {
        String result=null;
        JSONArray resultJSONArray = new JSONArray();
        try {
            List<Map<String ,Object>> orderResultList=  customerDao.queryOrderMore(orderId);
            if(null!=orderResultList && orderResultList.size()!=0){
                for(Map<String, Object> orderResult : orderResultList){
                    JSONObject orderJSON = JSONObject.fromObject(orderResult);
                    String taskType = (String) orderJSON.get("task_type");
                    switch(taskType){
                        case "0":
                            orderJSON.put("task_type", "域名解析");
                            break;
                        case "1":
                            orderJSON.put("task_type", "缓存刷新");
                            break;
                        default: break;
                    }
                    resultJSONArray.add(orderJSON);
                }
                result = resultJSONArray.toString();
            }else{
                JSONObject JSONerror = new JSONObject();
                JSONerror.put("errorCode","1");
                JSONerror.put("errorMessage","无订单信息");
                result = JSONerror.toString();
            }
        }
        catch (Exception e){
            log.error("查询订单信息异常：",e);
        }finally {
            return result;
        }
    }
    /**
     * 查询所有省份信息
     * @return
     */
    @Override
    public String getAllProvinces() {
        JSONArray result = new JSONArray();
        try {
            //查询处于在途中的解析类订单任务
            Map param = new HashMap();
            param.put("VALIDFLAG","0"); //0 表示有效
            param.put("AREA_LEVEL","1");
            List<Map<String,Object>> areaList = customerDao.getAllProvinces(param);
            for( Map<String,Object> areaResult:areaList){
                JSONObject areaJson= JSONObject.fromObject(areaResult);
                result.add(areaJson);
            }
        }catch (Exception e){
            log.error("查询订单信息: ",e);
            result.add("8888");
        }finally {
            return result.toString();
        }
    }
    /**
     * 根据客户ID查询域名及子域名
     * @param custId
     * @return
     */
    @Override
    public String queryRootDomainName(String custId) {
        String result=null;
        JSONObject JSONObjectRe = new JSONObject();   //最终返回的JSON
        JSONArray resultJSON = new JSONArray();       //user的value值，即根域名列表
        try {
            List<Map<String ,Object>> domainnameResultList=  customerDao.queryDomainnameByIDAndType(custId, null);  //先查根域名，返回根域名的列表
            if (domainnameResultList == null || domainnameResultList.size() <=0){
                result="还未添加根域名 "+custId;
            }else{
                for (Map<String,Object> domain : domainnameResultList){
                    String type = (String)domain.get("type");
                    //如果是0 ，代表是跟域名
                    if ("0".equals(type)){
                        resultJSON.add(domain);
                    }
                }
                JSONObjectRe.put("user",resultJSON);
                result = JSONObjectRe.toString();
            }
        }
        catch (Exception e){
            log.error("查询域名信息异常：",e);
        }finally {
            return result;
        }
    }
}
